package com.lovo.cloud.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author luo
 * @description
 * @date 2020/12/5 10:52
 */
@Configuration
public class MQConfig {
    //注入工厂（已经预加载）
    @Autowired
    CachingConnectionFactory connectionFactory;

    //rabbitmq模板
    @Bean(value = "rabbitTemplate")
    public RabbitTemplate rabbitTemplate() {

        return new RabbitTemplate(connectionFactory);
    }

    //死信队列
    @Bean
    public Queue deadQueue(){
        return new Queue("deadQueue");
    }

    //死信交换机
    @Bean
    public DirectExchange deadExchange(){
        return  new DirectExchange("deadExchange");
    }

    //死信交换机队列绑定
    @Bean
    public Binding deadQueueToDeadExchange(Queue deadQueue, DirectExchange deadExchange){
        return  BindingBuilder.bind(deadQueue).to(deadExchange).with("dead_routing_key");
    }

    @Bean
    public Queue createPointQueue(){
        //关联死信交换机
        Map<String, Object> args = new HashMap<>(6);
        // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", "deadExchange");
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key","dead_routing_key");
        // x-message-ttl  声明队列的TTL
        args.put("x-message-ttl",30000);
        return QueueBuilder.durable("j177_point").withArguments(args).build();
    }

    //创建交换机
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("directExchange");
    }

    //把队列绑定到交换机
    @Bean
    public Binding createPointQueueToDirectExchange(
            Queue createPointQueue,
            DirectExchange directExchange){
        return BindingBuilder.bind(createPointQueue).to(directExchange)
                .with("order");
    }

}
